import {Form, Upload, Radio, Input, Button, Space, message} from "antd";
import { PlusOutlined } from '@ant-design/icons';
import ReactQuill from "react-quill";
import 'react-quill/dist/quill.snow.css';
import './index.less'
import {useEffect, useRef, useState} from "react";
import {postArticles, putArticles} from "../../api/publish";
import Channels from "../../components/channels";
import {useLocation, useNavigate} from "react-router-dom";
import {getArticlesDetails} from "../../api/articles";

function Publish(props) {
    const navigate=useNavigate()
    const articlesInfo=useLocation()
    const [form]=Form.useForm()
    //发布或草稿（状态）
    const isDraft=useRef(false)
    // 控制Upload组件图片上传数量，默认值为：1 表示默认选中的是单图
    const [maxCount, setMaxCount] = useState(1)
    //封面图片展示列表
    const [fileList, setFileList] = useState([]);
    // 创建存储所有图片的 ref 对象
    // 这个 ref 对象，就是存储所有已上传图片的仓库（数据源），将来要用几张，就从 ref 中获取几张
    const fileListRef = useRef([])
    //回写文章编辑信息
    useEffect(()=>{
        const {id}=articlesInfo?.state?articlesInfo.state:{}
        // console.log(articlesInfo)
        if (articlesInfo.state){
            getArticlesDetails(id).then((res)=>{
                console.log(res)
                const { title, content, channel_id,cover}=res.data
                if (res.message=='OK'){
                    form.setFieldsValue({
                        title,
                        content,
                        channel_id,
                        type:cover.type
                    })
                    fileListRef.current=cover.images.map((item)=>{
                        return {url:item}
                    })
                    setFileList(fileListRef.current)
                    // handleGroupChange(cover.type)
                }
            })

        }
    },[articlesInfo])
    //上传图片
    const handleUploadChange = info => {
        // console.log(info)
        const newFileList = info.fileList.map(file => {
            if (file.response) {
                // 有响应数据的时候
                return {
                    url: file.response.data.url
                }
            }
            return file
        })
        // 将已上传的图片，存储到 ref 对象中
        fileListRef.current = newFileList
        setFileList(newFileList)
        // console.log(fileList)
    }
    //上传数量
    const handleGroupChange=({target})=>{
        // console.log(target.value)
        setMaxCount(target.value)
        if (target.value===1){
            const newFileList = fileListRef.current[0] ? [fileListRef.current[0]] : []
            setFileList(newFileList)
        }else if(target.value===3){
            setFileList(fileListRef.current||[])
        }else {
            setFileList([])
        }
    }
    //提交
    const onFinish = (values) => {
        // console.log('Received values of form: ', values);
        const {title,content,type,channel_id}=values
        const data={
            title,
            content,
            channel_id,
            cover: {
                type,
                images: fileList.map(item => item.url)
            }
        }
        //编辑文章
        if (articlesInfo.state){
            putArticles(articlesInfo.state.id,isDraft.current,data).then((res)=>{
                console.log(res)
                if (res.message==='OK'){
                    // console.log(isDraft.current)
                    message.success(isDraft.current?'存入草稿成功':'编辑成功');
                    navigate('/home/article')
                }
                //复原发布模式
                isDraft.current=false
            })
        }else {  //发布文章
            postArticles(isDraft.current,data).then((res)=>{
                console.log(res)
                if (res.message==='OK'){
                    message.success(isDraft.current?'存入草稿成功':'编辑成功');
                    navigate('/home/article')
                }
                //复原发布模式
                isDraft.current=false
            })
        }

        // console.log(data)
    };
    //草稿
    const handlePublishDraft=()=>{
        //开启草稿模式
        isDraft.current=true
        // console.log(isDraft.current)
        form.validateFields().then((res)=>{
            // console.log(res)
            onFinish(res)
        })
    }
    return (
        <div>
            <Form
                name="validate_other"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                onFinish={onFinish}
                initialValues={{ type: 1, content: '' }}
                form={form}
            >
                {/*标题*/}
                <Form.Item
                    name="title"
                    label="标题"
                    rules={[{required: true, message: 'Please input your name',},]}
                >
                    <Input placeholder="Please input your name" />
                </Form.Item>
                {/* 频道 */}
                <Form.Item
                    name="channel_id"
                    label="频道"
                    rules={[{ required: true, message: 'Please select your country!' }]}
                >
                        <Channels/>
                </Form.Item>
               {/* 封面 */}
                <Form.Item label="封面">
                    <Form.Item name="type">
                        <Radio.Group onChange={handleGroupChange}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                            {/* <Radio value={-1}>自动</Radio> */}
                        </Radio.Group>
                    </Form.Item>
                    {maxCount !== 0 && (
                        <Upload
                            name="image"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList
                            action="http://geek.itheima.net/v1_0/upload"
                            multiple={maxCount === 3}
                            maxCount={maxCount}
                            fileList={fileList}
                            onChange={handleUploadChange}
                        >
                            {fileListRef.current.length===3?null:(<div style={{marginTop: 8}}><PlusOutlined/></div>)}
                        </Upload>
                    )}
                </Form.Item>
            {/*内容-富文本*/}
                <Form.Item
                    label="内容"
                    name="content"
                    rules={[{ required: true, message: '请输入文章内容' }]}
                >
                    <ReactQuill
                        className="publish-quill"
                        theme="snow"
                        placeholder="请输入文章内容"
                    />
                </Form.Item>
                {/*按钮*/}
                <Form.Item wrapperCol={{ offset: 4 }}>
                    <Space>
                        <Button size="large" type="primary" htmlType="submit">
                            {articlesInfo.state?'编辑文章':'发布文章'}
                        </Button>
                        <Button size="large" onClick={handlePublishDraft}>
                            存入草稿
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Publish;
